package com.itheima.aop;

import com.itheima.annotation.FlashFTL;
import com.itheima.config.FreeMarkerProperties;
import com.itheima.enumeration.OperationType;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class FlashFTLAOP {
    // 文件名
    public static final String FTL_SETMEAL_LIST_NAME = "mobile_setmeal";
    public static final String FTL_SETMEAL_NAME = "mobile_setmeal_detail";
    public static final String HTML_SETMEAL_LIST_NAME = "setmeal";
    public static final String HTML_SETMEAL_NAME = "setmeal_detail";

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private FreeMarkerProperties freeMarkerProperties;

    @Pointcut("@annotation(com.itheima.annotation.FlashFTL)")
    public void flashFTL() {
    }

    /**
     * 生成套餐静态页面
     *
     * @param joinPoint
     * @throws Throwable
     */
    @After("flashFTL()")
    public void flashFTL(JoinPoint joinPoint) {
        log.info("刷新套餐列表静态页面");
        try {
            Configuration configuration = freeMarkerConfigurer.getConfiguration();

            // 更新套餐列表静态页面
            List<Setmeal> setmealList = setmealService.findAll();
            Template template = configuration.getTemplate(FTL_SETMEAL_LIST_NAME + ".ftl");
            Map<String, Object> model = new HashMap<>();
            model.put("setmealList", setmealList);
            log.info("更新套餐列表静态页面：{}", setmealList);
            template.process(model, new FileWriter(freeMarkerProperties.getOutputPath() + HTML_SETMEAL_LIST_NAME + ".html"));

            // 根据类型执行套餐详情的静态页面操作
            OperationType type = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(FlashFTL.class).type();
            Integer id;
            switch (type) {
                case INSERT:
                    id = ((Setmeal) joinPoint.getArgs()[0]).getId();
                    insertSetmealDetailFTL(id, configuration);
                    break;
                case DELETE:
                    // 根据id删除页面
                    id = ((Integer) joinPoint.getArgs()[0]);
                    deleteSetmealDetailFTLById(id);
                    break;
                case UPDATE:
                    // 删除页面并新增
                    id = ((Setmeal) joinPoint.getArgs()[0]).getId();
                    deleteSetmealDetailFTLById(id);
                    insertSetmealDetailFTL(id, configuration);
                    break;
                case FLASH:
                    for (Setmeal each : setmealList) {
                        id = each.getId();
                        deleteSetmealDetailFTLById(id);
                        insertSetmealDetailFTL(id, configuration);
                    }
                    break;
                default:
                    break;
            }
            // 默认操作
            flashSetmealList(configuration);
        } catch (Exception e) {
            log.error("刷新套餐静态页面失败: {}", String.valueOf(e));
        }
    }

    /**
     * 刷新套餐列表静态页面
     *
     * @throws Exception
     */
    private void flashSetmealList(Configuration configuration) throws Exception {}

    /**
     * 删除套餐详情静态页面
     * @param id
     */
    private void deleteSetmealDetailFTLById(Integer id) {
        File file = new File(freeMarkerProperties.getOutputPath() + HTML_SETMEAL_NAME + "_" + id + ".html");
        if (file.exists()) {
            boolean delete = file.delete();
        }
    }

    /**
     * 生成套餐详情静态页面
     * @param id
     * @param configuration
     * @throws Exception
     */
    private void insertSetmealDetailFTL(Integer id, Configuration configuration) throws Exception {
        Setmeal setmeal = setmealService.findById(id, true);
        Template template = configuration.getTemplate(FTL_SETMEAL_NAME + ".ftl");
        Map<String, Object> model = new HashMap<>();
        model.put("setmeal", setmeal);
        log.info("更新套餐详情静态页面：{}", setmeal);
        template.process(model, new FileWriter(freeMarkerProperties.getOutputPath() + HTML_SETMEAL_NAME + "_" + id + ".html"));

    }

}
